package com.xuliugen.security.core;

import com.xuliugen.security.model.Authority;
import com.xuliugen.security.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by xuliugen on 2017/11/8.
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 根据用户标识获取用户
        //TODO 去获取数据库中真实的用户
        User user = new User(1L, "xuliugen", passwordEncoder.encode("123456"), "xu", "liugen", "1573876303@qq.com", true, new Date());

        // 2. 获取用户权限
        //TODO 去查找用户真正的权限
        List<Authority> authorities = new ArrayList<>();
        authorities.add(new Authority(1L, "ADMIN"));

        user.setAuthorities(authorities);

        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            return JwtUserFactory.create(user);
        }
    }
}
